package com.cardbaobao.cardbabyclient.ui.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.callback.RecycleItemClickedCallback;
import com.cardbaobao.cardbabyclient.controller.Controller;
import com.cardbaobao.cardbabyclient.expand.snap.LeftAlignSnapHelper;
import com.cardbaobao.cardbabyclient.model.QrCodeDebitFeeRateData;
import com.cardbaobao.cardbabyclient.model.QrCodeDebitOrder;
import com.cardbaobao.cardbabyclient.model.result.QrCodeDebitOrderResult;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.ui.adapter.QrCodeDebitChannelAdapter;
import com.cardbaobao.cardbabyclient.ui.helper.DebitHelper;
import com.cardbaobao.cardbabyclient.ui.pop.NumberKeyBoardPop;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.JsonUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.widget.TitleBar;
import com.gyf.barlibrary.ImmersionBar;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import rx.Subscriber;

/**
 * Created by Jiangzx on 2017/9/4 16:07.
 * 二维码收款
 */

public class QrCodeDebitActivity extends BaseActivity {
    public static final String DEBIT_AMOUNT_S="debitAmount";
    public static final String DEBIT_FEE_S="debitFee";
    public static final String DEBIT_ARRIVAL_S="arrival";
    public static final String DEBIT_RATE_O="rate";

    @BindView(R.id.title_bar)
    TitleBar titleBar;
    @BindView(R.id.et_amount)
    EditText etAmount;
    @BindView(R.id.ibt_delete)
    ImageButton ibtDelete;
    @BindView(R.id.ll_pre_view)
    LinearLayout llPreView;
    @BindView(R.id.tv_fee)
    TextView tvFee;
    @BindView(R.id.tv_amount_money)
    TextView tvAmountMoney;


    @BindView(R.id.tv_rate)
    TextView tvRate;
    @BindView(R.id.tv_settlement)
    TextView tvSettlement;
    @BindView(R.id.tv_quota)
    TextView tvQuota;

    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    QrCodeDebitChannelAdapter adapter;

    private ArrayList<QrCodeDebitFeeRateData.FeeRate> qrCodeRates;
    private QrCodeDebitFeeRateData.FeeRate rate;//获取费率



    @Override
    protected int getLayoutId() {
        return R.layout.activity_qr_code_debit;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        titleBar.setTitleText("二维码收银台");
        ImmersionBar.with(this).statusBarDarkFont(true,Constant.STATUS_BAR_FONT_ALPHA).init();
        //处理输入框光标
        try{
            Class<EditText> cls = EditText.class;
            Method setShowSoftInputOnFocus;
            setShowSoftInputOnFocus = cls.getMethod(
                    "setShowSoftInputOnFocus", boolean.class);
            setShowSoftInputOnFocus.setAccessible(true);
            setShowSoftInputOnFocus.invoke(etAmount, false);
        }catch (Exception e){
            e.printStackTrace();
        }
        titleBar.setLeftViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mCurrentPageId=Self.Page.app_qrcode_cashier;

        titleBar.setRightViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SelfUtils.buriedClickData(Self.Action.app_click_qrcode_cashier_common_problem,
                        Self.Action.app_click_qrcode_cashier_common_problem_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);

                Controller controller=new Controller(mContext);
                controller.toCommonQuestion(QrCodeDebitActivity.this,mCurrentPageId);
            }
        });
        resetPreViewUi();
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        //处理费率
        qrCodeRates=getIntent().getParcelableArrayListExtra(FeeRateActivity.QR_CODE_DEBIT_FEE_RATE_LIST_ARRAY);

        adapter=new QrCodeDebitChannelAdapter(mContext,qrCodeRates);
        adapter.setCallback(new RecycleItemClickedCallback() {
            @Override
            public void onRecycleItemClicked(int position) {
                adapter.setSelected(position);
                rate=qrCodeRates.get(position);
                setRatesUi(rate);
                changePreViewValue(etAmount.getText().toString().trim());
                showPopKeyboard();
            }
        });


        LinearLayoutManager layoutManager=new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(layoutManager);
        LeftAlignSnapHelper helper=new LeftAlignSnapHelper();
        helper.attachToRecyclerView(recyclerView);
        recyclerView.setAdapter(adapter);

        rate=adapter.getSelected();
        setRatesUi(rate);
    }

    private void setRatesUi(QrCodeDebitFeeRateData.FeeRate rate){
        tvRate.setText(
                (String.format(Locale.CHINESE, Constant.AMOUNT_FORMAT,Double.parseDouble(rate.getRate()))) +
                        "%");
        tvSettlement.setText(
                (String.format(Locale.CHINESE,Constant.AMOUNT_FORMAT,Double.parseDouble(rate.getEach_charge())))+
                        "元/笔");
        //判断是否为整数
        try{
            //转成整数
            long amount=Long.parseLong(rate.getHigh_position());
            if(amount>=10000){
                if(amount%10000==0){
                    tvQuota.setText("当天"+(amount/10000)+"万元");
                }else{
                    tvQuota.setText("当天"+ String.format(Locale.CHINESE, Constant.AMOUNT_FORMAT,amount/10000.0)
                                    +"万元");
                }
            }else{
                tvQuota.setText( "当天"+amount+"元");
            }
        }catch (Exception e){
            //转成小数
            tvQuota.setText("当天"+
                            String.format(Locale.CHINESE,Constant.AMOUNT_FORMAT,Double.parseDouble(rate.getHigh_position()))+
                            "元");
        }
    }

    private void resetPreViewUi(){
        tvFee.setText("0.00元");
        tvAmountMoney.setText("0.00元");
    }

    @OnTextChanged(R.id.et_amount)
    public void onTextChanged(CharSequence s, int start, int before, int count){
        if(s.length()>0){
            ibtDelete.setVisibility(View.VISIBLE);
        }else{
            ibtDelete.setVisibility(View.INVISIBLE);
            resetPreViewUi();
        }
    }


    DebitHelper.CalculateBean calculateBean;
    private void changePreViewValue(String amount){
        calculateBean= DebitHelper.calculateFee(amount,
                rate.getDiscount(),
                rate.getRate(),
                rate.getEach_charge());
        tvFee.setText(String.format(Locale.CHINESE,Constant.AMOUNT_FORMAT,calculateBean.getFee())+"元");
        tvAmountMoney.setText(String.format(Locale.CHINESE,Constant.AMOUNT_FORMAT,calculateBean.getSpace())+"元");
    }

    StringBuilder sb;
    private NumberKeyBoardPop pop;
    private void showPopKeyboard(){
        if(pop==null){
            pop=new NumberKeyBoardPop(mContext);
            pop.setNumberKeyListener(new NumberKeyBoardPop.OnKeyPressed() {
                @Override
                public void onKeyPressed(int key) {
                    if(sb==null){
                        sb=new StringBuilder();
                    }else{
                        sb.delete(0,sb.length());
                    }
                    sb.append(etAmount.getText().toString());
                    switch (key){
                        case NumberKeyBoardPop.OnKeyPressed.KEY_FINISH:
                            //收款
                            pop.dismiss();
                            //判断输入金额是否合理
                            String amount=sb.toString();
                            if(DebitHelper.checkInputAmount(amount)){
                                //计算输入金额是否在限额内
                                try{
                                    double low=Double.parseDouble(rate.getLow_position());
                                    double high=Double.parseDouble(rate.getHigh_position());
                                    double inputAmount=Double.parseDouble(etAmount.getText().toString().trim());
                                    if(inputAmount<low){
                                        ToastUtil.showToastLong("交易金额不能低于"+low+"元");
                                    }else if(inputAmount>high){
                                        ToastUtil.showToastLong("交易金额不能大于"+high+"元");
                                    }else{
                                        //埋点
                                        SelfUtils.buriedClickData(Self.Action.app_click_qrcode_cashier_receivables,
                                                Self.Action.app_click_qrcode_cashier_receivables_des,
                                                mEnterPageTime,
                                                mCurrentPageId,
                                                mPrePageId);

                                        qrCodeDebitOrder();
                                    }
                                }catch (Exception e){
                                    //输入金额错误
                                }
                            }
                            break;
                        case NumberKeyBoardPop.OnKeyPressed.KEY_DELETE:
                            //删除键
                            if(sb.length()>0){
                                sb.deleteCharAt(sb.length()-1);
                            }
                            break;
                        case NumberKeyBoardPop.OnKeyPressed.KEY_ONE:
                            //数字键1
                        case NumberKeyBoardPop.OnKeyPressed.KEY_TWO:
                            //数字键2
                        case NumberKeyBoardPop.OnKeyPressed.KEY_THREE:
                            //数字键3
                        case NumberKeyBoardPop.OnKeyPressed.KEY_FOUR:
                            //数字键4
                        case NumberKeyBoardPop.OnKeyPressed.KEY_FIVE:
                            //数字键5
                        case NumberKeyBoardPop.OnKeyPressed.KEY_SIX:
                            //数字键6
                        case NumberKeyBoardPop.OnKeyPressed.KEY_SEVEN:
                            //数字键7
                        case NumberKeyBoardPop.OnKeyPressed.KEY_EIGHT:
                            //数字键8
                        case NumberKeyBoardPop.OnKeyPressed.KEY_NINE:
                            //数字键9
                            String str=sb.toString();
                            if(str.contains(".")){
                                //精确到小数点后两位
                                int index=str.indexOf('.');
                                if(str.length()-index-1<2){
                                    sb.append(key);
                                }
                            }else{
                                sb.append(key);
                            }
                            break;
                        case NumberKeyBoardPop.OnKeyPressed.KEY_ZERO:
                            //数字键0
                            String text=sb.toString();
                            //精确到小数点后2位
                            if(text.length()>0){
                                if(text.contains(".")){
                                    int index=text.indexOf('.');
                                    if(text.length()-index-1<2){
                                        sb.append(key);
                                    }
                                }else{
                                    if(!text.startsWith("0")){
                                        sb.append(key);
                                    }
                                }
                            }
                            break;
                        case NumberKeyBoardPop.OnKeyPressed.KEY_DOT:
                            //小数点
                            if(!sb.toString().contains(".")){
                                if(sb.length()!=0){
                                    sb.append(".");
                                }
                            }
                            break;
                    }

                    //限制输入字符数
                    if(sb.length()>8){
                        etAmount.setText(sb.substring(0,8));
                    }else{
                        etAmount.setText(sb.toString());
                    }

                    changePreViewValue(sb.toString());
                    try{
                        etAmount.setSelection(etAmount.getText().length());
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            });
        }
        if(!pop.isShowing()){
            pop.showAtLocation(etAmount, Gravity.BOTTOM,0,0);
        }
    }

    private void qrCodeDebitOrder() {
        showProgressDialog(false);
        Api.qrCodeDebitOrder(String.valueOf(mApplication.getUser().getID()),
                String.valueOf(calculateBean.getAmount()),
                rate.getChannel_type(),
                String.valueOf(calculateBean.getFee()),
                String.valueOf(calculateBean.getSpace())).
                subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable throwable) {
                        dismissProgressDialog();
                        ToastUtil.showToast(ApplicationHelper.getApplicationContext().
                                getString(R.string.string_request_server_fail));
                    }

                    @Override
                    public void onNext(String s) {
                        dismissProgressDialog();
                        QrCodeDebitOrderResult result= JsonUtil.json2Object(s,QrCodeDebitOrderResult.class);
                        if(result.getCode()==Constant.SUC_CODE){
                            QrCodeDebitOrder order=result.getData();
                            if(order!=null){
                                Intent intent=new Intent(mContext,QrCodeDebitShowActivity.class);
                                intent.putExtra(FeeRateActivity.QR_CODE_DEBIT_FEE_RATE_LIST_ARRAY,
                                        qrCodeRates);
                                intent.putExtra(DEBIT_RATE_O,
                                        rate);
                                intent.putExtra(DEBIT_AMOUNT_S,
                                        String.valueOf(calculateBean.getAmount()));
                                intent.putExtra(DEBIT_FEE_S,
                                        String.valueOf(calculateBean.getFee()));
                                intent.putExtra(DEBIT_ARRIVAL_S,
                                        String.valueOf(calculateBean.getSpace()));
                                intent.putExtra(QrCodeDebitShowActivity.QR_CODE_CONTENT_S,
                                        order.getOther_qRcodeURL());
                                intent.putExtra(QrCodeDebitShowActivity.QR_CODE_DEBIT_ORDER_NUMBER_S,
                                        order.getOther_orderNo());
                                intent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                                startActivity(intent);
                                finish();
                            }
                        }else{
                            ToastUtil.showToast(result.getMsg());
                        }
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        GoogleAnalyticsUtil.setScreenName("二维码收款");
    }

    @OnClick({R.id.et_amount,R.id.ibt_delete})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.et_amount:
                showPopKeyboard();
                break;
            case R.id.ibt_delete:
                etAmount.setText("");
                break;
        }
    }
}
